﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Ymatou.ServiceCenter
{
    /// <summary>
    /// 写配置文件
    /// </summary>
    internal class FileWriter
    {
        private static readonly object Locker = new object();
        private static readonly Dictionary<string, object> FileMap = new Dictionary<string, object>();

        public static void Write(string filePath, string content)
        {
            if (!FileMap.Keys.Contains(filePath, StringComparer.InvariantCultureIgnoreCase))
            {
                lock (Locker)
                {
                    if (!FileMap.Keys.Contains(filePath, StringComparer.InvariantCultureIgnoreCase))
                    {
                        FileInfo fileInfo = new FileInfo(filePath);
                        if (fileInfo.Directory != null && !fileInfo.Directory.Exists)
                        {
                            fileInfo.Directory.Create();
                        }

                        FileMap.Add(filePath, new object());
                    }
                }
            }

            lock (FileMap[filePath])
            {
                File.WriteAllText(filePath, content);
            }
        }
    }
}
